<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Front extends CI_Controller {

	function __construct()
	{
		parent::__construct();
		$this->load->model('frontmodel');
		$this->load->library('form_validation');
	}

	public function signin()
	{
		$this->load->view('front/v_signin');
	}	

	public function signup()
	{
		$this->load->view('front/v_signup');	
	}

	public function masuk(){
		// $this->form_validation->set_error_delimiters('<p class="alert alert-danger">', '</p>');
		$this->form_validation->set_rules('user_name', 'Username', 'required|xss_clean|callback_status_check');
		$this->form_validation->set_rules('password', 'Password', 'required|xss_clean');
		$this->form_validation->set_message('required', '%s tidak boleh kosong');
		if($this->form_validation->run() == FALSE)
		{
			$this->load->view('front/v_signin');
		}
		else
		{
			$this->usermasuk();
		}
	}

	public function status_check()
	{
		$cekstatus = $this->frontmodel->cekdb();

		if ($cekstatus == null)
		{	
		$this->form_validation->set_message('status_check', 'Username atau password salah.');
		return FALSE;
		}
		else
		{

		return TRUE;

		}
	}

	function cekuser() {
		$data['username'] = $this->input->post('user_name'); 
		$data['pass'] = ($this->input->post('password')); 
		$data['hasil'] = $this->frontmodel->cekdb(); 

		if($data['hasil'] == null) { 
			return "no"; 
		} 
		else { 
			return "yes"; 
		}
	} 

	function usermasuk() 
	{ 
		//jika benar
		if($this->cekuser() == "yes") 
		{
			$data['user_name'] 	 =  $this->input->post('user_name');
			$data['password'] 	 =  md5($this->input->post('password')); 
			$ambil = $this->frontmodel->cekdb();
			
			foreach($ambil as $row)
			{
				$data['role']  		= $row->ROLE;
				$data['id_user']  	= $row->ID_USER;
				$data['pemohon'] 	= $row->ID_PEMOHON;
			}
			/* echo $data['id_user']; */

			$newdata = array(
				'user_name' 	=> $data['user_name'], 
				'password' 		=> $data['password'], 
				'role' 			=> $data['role'], 
				'id_user' 		=> $data['id_user'] , 
				'pemohon' 		=> $data['pemohon'], 
				'isLoggedIn'	=> TRUE
			); 
			$this->session->set_userdata($newdata);
			/* echo ($this->session->userdata('role')) ;	 */ 
			
			$ambil = $this->frontmodel->cekdb();

			//$data['tampil'] = 
			/*  $data['show'] = $this->frontmodel->get_pemohon($data['user_name']);
			$data['main']= 'pengajuan/v_permohonan';
			$this->load->view('v_template',$data); */
			if($this->session->userdata('role') == 3)
				redirect('admin/adlegalisir/persetujuan');
			else if ($this->session->userdata('role') == 4)
				redirect('admin/adlegalisir/persetujuan');
			else if ($this->session->userdata('role') == 6)
				redirect('admin/adlegalisir/j_permohonan/1');
			else if ($this->session->userdata('role') == 7)
				redirect('admin/adlegalisir/j_permohonan/1');
			else if ($this->session->userdata('role') == 1)
				redirect('admin/adlegalisir/permohonan');
			else if ($this->session->userdata('role') == 2)
				redirect('admin/adlegalisir/permohonan');
			else
				redirect('front/halaman_utama');
			/* if($data["hasil"] == "admin"){
			$this->load->view('loginadmin');
			}elseif ($data["hasil"] == "user"){
			$this->load->view('loginuser');
			}elseif($data["hasil"] == "operator"){
			$this->load->view('loginoperator');
			}else{
			echo "error";
			} */	 
			/* $this->load->view('loginsukses', $data);  */
		} 
		//jika salah
		else 
		{ 
			echo "Login gagal"; 
			$this->load->view('front/v_signin');
		} 
	}

	public function halaman_utama(){
		$id_user = $this->session->userdata('id_user');
		$id = $id_user;
		/* echo $id_user; */
		$datas['hasil'] = $this->frontmodel->cekPemohon($id_user); 

		if($datas['hasil'] == null) {
			$this->load->model("m_data_sekolah");
			$data["sd"]		= $this->m_data_sekolah->get_by(array("JENJANG"=>"MI","JENJANG"=>"SD"),FALSE,TRUE);
			$data["smp"]	= $this->m_data_sekolah->get_by(array("JENJANG"=>"MTS","JENJANG"=>"SMP"),FALSE,TRUE);
			$data["sma"]	= $this->m_data_sekolah->get_by(array("JENJANG"=>"MA","JENJANG"=>"SMA","JENJANG"=>"SMK"),FALSE,TRUE);
			$username		= $this->session->userdata('user_name');
			$data['show']	= $this->frontmodel->get_pemohon($username);
			$data['title']	= '| Permohonan Legalisir Baru';
			$data['main']	= 'pengajuan/v_permohonan';
			$this->load->view('v_template',$data); 
		} 
		else { 
			redirect('pengajuan');
		}
	}

	public function aktivasiLogin()
	{
		$activation_code = md5($this->input->post('password'));

		// field name, error message, validation rules
		$this->form_validation->set_rules('nama_lengkap', 'Nama Lengkap', 'required');
		$this->form_validation->set_rules('user_name', 'User Name', 'required|min_length[4]|max_length[10]|xss_clean|callback_username_check');
		/* $this->form_validation->set_rules('user_name', 'User Name', ''); */
		$this->form_validation->set_rules('email', 'Your Email', 'required|valid_email|callback_email_check');
		/* $this->form_validation->set_rules('email_address', 'Your Email', ''); */
		$this->form_validation->set_rules('password', 'Password', 'required|min_length[4]|max_length[32]');
		$this->form_validation->set_rules('con_password', 'Password Confirmation', 'required|matches[password]');

		if($this->form_validation->run() == FALSE)
		{
			/* $data['error']="Ada field yang belum diisi/salah"; */
			// $this->load->view('front/v_signup');
			echo "error";
		}
		else
		{
			$this->frontmodel->add_user();
			$this->frontmodel->add_pemohon();
			$this->frontmodel->update_user();
			echo "success";
			/* $this->thank(); */
			// $config = Array(
			// 'protocol' 		=> 'smtp',
			// 'smtp_host' 	=> 'ssl://smtp.googlemail.com',
			// 'smtp_port' 	=> 465,
			// 'smtp_user' 	=> 'dobolpol@gmail.com',
			// 'smtp_pass' 	=> 'dobolpolnjedug87',
			// 'mailtype'  	=> 'html', 
			// 'smtp_timeout'	=> 30,
			// 'charset'   	=> 'iso-8859-1'
			// );
			// $this->load->library('email', $config);
			// $this->email->set_newline("\r\n");

			// $this->email->from('dobolpol@gmail.com', 'allen');
			// $this->email->to($this->input->post('email_address')); 

			// $this->email->subject('Confirmation');
			/* $this->email->message('http://localhost:8787/legalisironline/front/activation'); */
			// $this->email->message('Click the link below to activate your account ' . anchor(base_url('front/activation/' . $activation_code),'Confirmation Register'));		

			// $result = $this->email->send();

			// $this->load->view('front/v_signin');
		}
	}

	public function autoSuggest()
	{
		if ( !isset($_GET['term']) )
		exit;
		$term = $_REQUEST['term'];
		$data = array();
		$rows = $this->frontmodel->getDataSekolah($term);
		foreach( $rows as $row )
		{
		$data[] = array(
		'label'=>$row->NAMA,
		'value' => $row->NAMA);
		// here i am taking name as value so it will display name in text field, you can change it as per your choice.
		}
		echo json_encode($data);
		flush();
	}

	public function lupaPass()
	{
		$this->load->view('front/v_lupaPass');	
	}

	public function username_check($str)
	{
		$cekuser = $this->frontmodel->cekuser($str);

		if ($cekuser == null)
		{
			return TRUE;
		}
		else
		{
			$this->form_validation->set_message('username_check', 'Username <b>'.$str.'</b> sudah terpakai.');
			return FALSE;
		}
	}

	public function email_check($str)
	{
		$cekemail = $this->frontmodel->cekemail($str);

		if ($cekemail == null)
		{
			return TRUE;
		}
		else
		{
			$this->form_validation->set_message('email_check', 'Email <b>'.$str.'</b> sudah terpakai.');
			return FALSE;
		}
	}
	public function emaillupa_check($str)
	{
		$cekemail = $this->frontmodel->cekemail($str);

		if ($cekemail == null)
		{
			$this->form_validation->set_message('emaillupa_check', 'Email '.$str.' Belum Ada');
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}

	public function statuslupa_check()
	{
		$cekstatuslupa = $this->frontmodel->ceklupa();

		if ($cekstatuslupa == null)
		{

			$this->form_validation->set_message('statuslupa_check', 'Anda Belum Verifikasi Email');
			return FALSE;
		}
		else
		{

		return TRUE;

		}
	}


	function doForget()
	{
		$this->form_validation->set_rules('email_address', 'Isi Email', 'required|callback_emaillupa_check|callback_statuslupa_check');
		/* $this->form_validation->set_rules('email_address', 'Your Email', '');
		$this->form_validation->set_rules('email_address', 'Your Status', ''); */

		if($this->form_validation->run() == FALSE)
		{
			/* $data['error']="Ada field yang belum diisi/salah"; */
			$this->load->view('front/v_lupaPass');
		}
		else
		{
			$this->load->helper('url');
			$email= $_POST['email_address'];
			$q = $this->db->query("select * from user where EMAIL='" . $email . "'");
			if ($q->num_rows > 0) {
			$r = $q->result();
			$user=$r[0];
			$this->resetpassword($user);
		}


		/* $info= "Password has been reset and has been sent to email id: ". $email;
		/* redirect('/index.php/login/forget?info=' . $info, 'refresh'); */
		}
		/* $error= "The email id you entered not found on our database "; */
		/* redirect('/index.php/login/forget?error=' . $error, 'refresh'); */ 

	} 
	private function resetpassword($user)
	{
		$config = Array(
		'protocol' => 'smtp',
		'smtp_host' => 'ssl://smtp.googlemail.com',
		'smtp_port' => 465,
		'smtp_user' => 'dobolpol@gmail.com',
		'smtp_pass' => 'dobolpolnjedug87',
		'mailtype'  => 'html', 
		'charset'   => 'iso-8859-1'
		);
		$this->load->library('email', $config);
		$this->email->set_newline("\r\n");

		date_default_timezone_set('GMT');
		$this->load->helper('string');
		$password= random_string('alnum', 8);
		$this->db->where('ID_USER', $user->ID_USER);
		$this->db->update('user',array('PASSWORD'=>MD5($password)));
		$this->load->library('email');
		$this->email->from('dobolpol@gmail.com', 'Allen');
		$this->email->to($user->EMAIL); 	
		$this->email->subject('Password reset');
		$this->email->message('You have requested the new password, Here is you new password:'. $password);	
		$this->email->send();
		$this->load->view('front/v_signin');
	} 

	public function activation()
	{
		$register_code = $this->uri->segment(3);
		$this->frontmodel->aktivasi_user($register_code);
		$this->load->view('front/v_aktivasiLogin');	
	}

	public function ubahPassword(){
		$this->form_validation->set_rules('pass_baru', 'New Password', 'min_length[4]|max_length[32]');
		$this->form_validation->set_rules('conpass', 'Password Confirmation', 'required|matches[pass_baru]');

		if($this->form_validation->run() == FALSE)
		{
			/* $data['error']="Ada field yang belum diisi/salah"; */
			$username	= $this->session->userdata('user_name');
			$data['show']	= $this->frontmodel->get_pemohon($username);
			$data['main']= 'pengajuan/v_ubahPass';
			$this->load->view('v_template',$data);
		}
		else
		{

			$this->frontmodel->ubahPass();
			$this->load->view('front/v_signin');
		}
	}
	
	public function redirect_approve()
	{
		$this->load->view('front/v_redirect_approve');
	}
	// public function datagrid(){
		// $data['main']= 'datagrid';
		// $this->load->view('v_template',$data);
	// }
	public function datatable(){
		$this->load->view("datatable");
	}
}

/* End of file front.php */
/* Location: ./application/controllers/front.php */